/**
 * Copyright (C) 2020-2021   江西省农村信用社联合社
 * All rights reserved
 */
package com.liuyucheng.idea_springboot.wechat.gzh.controller;

import cn.hutool.core.util.XmlUtil;
import com.liuyucheng.idea_springboot.wechat.gzh.entity.WxParam;
import com.liuyucheng.util.EmptyUtil;
import com.liuyucheng.util.JsonUtils;
import com.liuyucheng.util.XmlUtils;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.annotation.*;
import org.w3c.dom.Document;

import java.util.Map;

@Slf4j
@Api(tags = "微信消息接收服务")
@RestController
@RequestMapping("/wechat/msg")
public class WechatMsgController {

    private String webPath;

    /**
     * GET请求响应微信发送的Token验证
     * @param requestParam
     * @return
     */
    @GetMapping(value = "")
    @ApiOperation(value = "微信Token验证", notes = "微信Token验证")
    public Object verifyToken(WxParam requestParam) {
        log.info("微信Token验证：{}", JsonUtils.toString(requestParam));
        return requestParam.getEchostr();
    }

    /**
     * POST接收微信的事件消息
     */
    @ApiOperation(value = "接收微信事件消息", notes = "接收微信事件消息")
    @PostMapping(value = "")
    public String handlerMsg(@RequestBody String msgString, WxParam requestParam) throws Exception {
        if(EmptyUtil.isEmpty(msgString)){
            throw new Exception("接收微信事件消息异常");
        }

        Document parseXml = XmlUtil.parseXml(msgString);
        log.info("收到微信公众号事件推送：{}", XmlUtil.toStr(parseXml));
        log.info("requestParam：{}", requestParam);

        //把用户发送的内容解析出来
        Map<String, String> map = XmlUtils.parseXml(msgString);
        if(EmptyUtil.isEmpty(map)){
            return null;
        }

        String returnStr = "";

        /*
        {Content=006,
         CreateTime=1635412910,
          ToUserName=gh_b0233ef9c149,
           FromUserName=oJMT150sdMa8TTfmDE1dbayEcEyA,
            MsgType=text,
             MsgId=23413485254081321}
         */
        String msgType = map.get("MsgType");
        String event = map.get("Event");
        String content = map.get("Content");
        String myself = map.get("ToUserName");
        String eventKey = map.get("EventKey");
        String userOpenId = requestParam.getOpenid();
        long createTime = System.currentTimeMillis()/1000;

        if("text".equals(msgType)){
            if(content.contains("解除绑定") || content.contains("解绑")){
                returnStr = "<xml>\n" +
                        "  <ToUserName><![CDATA["+userOpenId+"]]></ToUserName>\n" +
                        "  <FromUserName><![CDATA["+myself+"]]></FromUserName>\n" +
                        "  <CreateTime>"+createTime+"</CreateTime>\n" +
                        "  <MsgType><![CDATA[text]]></MsgType>\n" +
                        "  <Content><![CDATA[您还没有绑定，无需解绑，如需绑定账户请<a href=\""+webPath+"/#/wechat/bindUser?path=/card/cardBill\">点击这里</a>。\n" +
                        "]]></Content>\n" +
                        "</xml>";
                return returnStr;
            }else if("绑定".equals(content) || "绑卡".equals(content) || "账号绑定".equals(content)){
                //绑定之前先查询是否已有绑定的账号，如果有，不提供绑定功能，进行提示
                returnStr = "<xml>\n" +
                        "  <ToUserName><![CDATA["+userOpenId+"]]></ToUserName>\n" +
                        "  <FromUserName><![CDATA["+myself+"]]></FromUserName>\n" +
                        "  <CreateTime>"+createTime+"</CreateTime>\n" +
                        "  <MsgType><![CDATA[text]]></MsgType>\n" +
                        "  <Content><![CDATA[如需绑定账户请<a href=\""+webPath+"/#/wechat/bindUser?path=/card/cardBill\">点击这里</a>。" +
                        "\n" +
                        "]]></Content>\n" +
                        "</xml>";
                return returnStr;
            }

            returnStr = "<xml>\n" +
                    "  <ToUserName><![CDATA["+userOpenId+"]]></ToUserName>\n" +
                    "  <FromUserName><![CDATA["+myself+"]]></FromUserName>\n" +
                    "  <CreateTime>"+createTime+"</CreateTime>\n" +
                    "  <MsgType><![CDATA[text]]></MsgType>\n" +
                    "  <Content><![CDATA[我好像没有听懂你说的话...如需绑定信用卡，请输入【绑定】，如需解除绑定信用卡，可以输入【解除绑定】或【解绑】]]></Content>\n" +
                    "</xml>";
            return returnStr;
        }else if("event".equals(msgType)){
            if("subscribe".equals(event)){
                returnStr = "<xml>\n" +
                        "  <ToUserName><![CDATA["+userOpenId+"]]></ToUserName>\n" +
                        "  <FromUserName><![CDATA["+myself+"]]></FromUserName>\n" +
                        "  <CreateTime>"+createTime+"</CreateTime>\n" +
                        "  <MsgType><![CDATA[text]]></MsgType>\n" +
                        "  <Content><![CDATA[欢迎关注百福信用卡微信公众号！您已绑定信用卡账户，点击公众号菜单，即可享受相关服务：\n(1)秒查账单、额度\n(2)想分就分，办理分期\n(3)签约还款，及时方便]]></Content>\n" +
                        "</xml>";
                return returnStr;
            }else if("CLICK".equals(event)){
                if("scoreQuery".equals(eventKey) || "getRights".equals(eventKey)){
                    returnStr = "<xml>\n" +
                            "  <ToUserName><![CDATA["+userOpenId+"]]></ToUserName>\n" +
                            "  <FromUserName><![CDATA["+myself+"]]></FromUserName>\n" +
                            "  <CreateTime>"+createTime+"</CreateTime>\n" +
                            "  <MsgType><![CDATA[text]]></MsgType>\n" +
                            "  <Content><![CDATA[敬请期待]]></Content>\n" +
                            "</xml>";
                }else if("V1001_GOOD".equals(eventKey)){
                    //如果点击了跳转小程序菜单,可以跳转到指定的小程序页面,并携带参数
                    String url = "pages/index/index";
                    return "<xml>\n" +
                            "<ToUserName><![CDATA["+userOpenId+"]]></ToUserName>\n" +
                            "<FromUserName><![CDATA["+myself+"]]></FromUserName>\n" +
                            "<CreateTime>"+createTime+"</CreateTime>\n" +
                            "<MsgType><![CDATA[event]]></MsgType>\n" +
                            "<Event><![CDATA[view_miniprogram]]></Event>\n" +
                            "<EventKey><![CDATA["+url+"]]></EventKey>\n" +
                            "<MenuId></MenuId>\n" +
                            "</xml>";
                }
                return returnStr;
            }
        }

        return null;
    }

}
